import { io, Socket } from 'socket.io-client';
import { toast } from 'react-hot-toast';
import { Message } from '@/types';

class SocketService {
  private socket: Socket | null = null;
  private messageHandlers: ((message: Message) => void)[] = [];
  private errorHandlers: ((error: any) => void)[] = [];
  private connectionHandlers: ((connected: boolean) => void)[] = [];
  private notesHandlers: ((payload: any) => void)[] = [];

  connect(token: string) {
    console.log('🔌 [DEBUG] socketService.connect() 开始');
    console.log('🔌 [DEBUG] 连接参数:', { hasToken: !!token, tokenLength: token?.length });
    
    if (this.socket?.connected) {
      console.log('⚠️ [DEBUG] Socket已连接，跳过重复连接');
      return;
    }

    console.log('🚀 [DEBUG] 创建新的Socket连接...');
    this.socket = io({
      auth: {
        token
      },
      transports: ['websocket', 'polling']
    });

    this.socket.on('connect', () => {
      console.log('✅ [DEBUG] Socket连接成功');
      console.log('🔌 [DEBUG] Socket ID:', this.socket?.id);
      this.connectionHandlers.forEach(handler => handler(true));
    });

    this.socket.on('disconnect', () => {
      console.log('❌ [DEBUG] Socket连接断开');
      this.connectionHandlers.forEach(handler => handler(false));
    });

    this.socket.on('new_message', (message: Message) => {
      console.log('📨 [DEBUG] 收到new_message事件:', message);
      this.messageHandlers.forEach(handler => handler(message));
    });

    this.socket.on('message_sent', (message: Message) => {
      console.log('📨 [DEBUG] 收到message_sent事件:', message);
      this.messageHandlers.forEach(handler => handler(message));
    });

    this.socket.on('notes_updated', (payload: any) => {
      console.log('📝 [DEBUG] 收到notes_updated事件:', payload);
      this.notesHandlers.forEach(h => h(payload));
    });

    this.socket.on('error', (error: any) => {
      console.error('❌ [DEBUG] Socket错误:', error);
      toast.error(error.message || '连接错误');
      this.errorHandlers.forEach(handler => handler(error));
    });

    this.socket.on('connect_error', (error) => {
      console.error('❌ [DEBUG] Socket连接错误:', error);
      toast.error('连接服务器失败');
    });
  }

  disconnect() {
    if (this.socket) {
      this.socket.disconnect();
      this.socket = null;
    }
  }

  sendMessage(content: string, type: 'text' | 'image' = 'text') {
    console.log('📤 [DEBUG] socketService.sendMessage() 开始');
    console.log('📤 [DEBUG] 发送参数:', { content, type });
    console.log('📤 [DEBUG] Socket状态:', { 
      hasSocket: !!this.socket, 
      isConnected: this.socket?.connected,
      socketId: this.socket?.id 
    });
    
    if (!this.socket?.connected) {
      console.log('❌ [DEBUG] Socket未连接，无法发送消息');
      toast.error('连接已断开，请刷新页面重试');
      return;
    }

    console.log('🚀 [DEBUG] 通过Socket发送消息...');
    this.socket.emit('send_message', {
      content,
      type
    });
    console.log('✅ [DEBUG] 消息已发送到Socket');
  }

  onMessage(handler: (message: Message) => void) {
    this.messageHandlers.push(handler);
    
    // 返回取消订阅函数
    return () => {
      const index = this.messageHandlers.indexOf(handler);
      if (index > -1) {
        this.messageHandlers.splice(index, 1);
      }
    };
  }

  onError(handler: (error: any) => void) {
    this.errorHandlers.push(handler);
    
    // 返回取消订阅函数
    return () => {
      const index = this.errorHandlers.indexOf(handler);
      if (index > -1) {
        this.errorHandlers.splice(index, 1);
      }
    };
  }

  isConnected(): boolean {
    return this.socket?.connected || false;
  }

  onNotesUpdated(handler: (payload: any) => void) {
    this.notesHandlers.push(handler);
    return () => {
      const i = this.notesHandlers.indexOf(handler);
      if (i > -1) this.notesHandlers.splice(i, 1);
    };
  }

  onConnectionChange(handler: (connected: boolean) => void) {
    this.connectionHandlers.push(handler);
    
    // 返回取消订阅函数
    return () => {
      const index = this.connectionHandlers.indexOf(handler);
      if (index > -1) {
        this.connectionHandlers.splice(index, 1);
      }
    };
  }
}

export const socketService = new SocketService();
export default socketService;